﻿/*
Description:特种流水卡批量打印
Copyright (c) : 通力凯顿（北京）系统集成有限公司
Writer:zhangrj
create Date:
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessRule.Business;
using System.Data;
using BusinessRule.Common;


public partial class forms_Custom_YePian_ContainerSpecialPrintForm : System.Web.UI.Page
{
    public string strHtml;//页面html代码
    public YPContainerBusiness ypBusiness = new YPContainerBusiness();
    public YPCommonBusiness common = new YPCommonBusiness();
    public List<Dictionary<string, object>> printSession;
    public DataTable dtMain;//批次基本信息
    public DataTable dtContainerStep;//工序信息
    public DataTable dtSpecResource;//设备型号
    public DataTable dtSpecCheckPoints;//关键过程控制记录
    public DataTable dtContainerAttributeDt;//特种信息
    public DataTable dtContainerSubContainer;//子工序信息
    public DataTable dtContainerStepAttributes;//批次工序属性信息 add zhunan 2022.1.19
    //public DataTable dtContainerStepCheckNotes;//批次工序检验备注信息
    public DataTable dtContainerSubInfo;//批次的子批次信息
    int totalHeight = 1000;//一页的高度(工序)
    int rowHeight = 400;//起始行高，内容表头的（工序）
    public int pages = 0;//全局页码
    public bool isBank = false;//是否空白
    public bool checkerNoEdit = true;
    //系统根路径
    string path = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                path = Request.Url.AbsoluteUri.ToString().Substring(0, Request.Url.AbsoluteUri.IndexOf("forms")) + "ImageTemp/";
                printSession = (List<Dictionary<string, object>>)Session["PrintInfo"];
                Session.Remove("PrintInfo");
                if (printSession != null && printSession.Count > 0)
                {
                    for (int i = 0; i < printSession.Count; i++)
                    {
                        rowHeight = 400;//起始行高，内容表头的  
                        pages = 0;//全局页码
                        isBank = false;//是否空白                        
                        strHtml += InitData(printSession[i], i + 1 == printSession.Count ? true : false);
                    }
                }
                else
                {
                    string ContainerId = Request["ContainerId"];
                    string WorkflowId = Request["WorkflowId"];
                    string IsBlank = Request["IsBlank"];
                    if (string.IsNullOrEmpty(ContainerId) || string.IsNullOrEmpty(WorkflowId) || string.IsNullOrEmpty(IsBlank))
                    {
                        ClientScript.RegisterStartupScript(ClientScript.GetType(), "myScript", "<script>alert('刷新无效，请关闭后重新打印');</script>");
                        return;
                    }
                    Dictionary<string, object> printInfo = new Dictionary<string, object>();
                    printInfo["ContainerId"] = ContainerId;
                    printInfo["WorkflowId"] = WorkflowId;
                    printInfo["IsBlank"] = Boolean.Parse(IsBlank);
                    strHtml += InitData(printInfo, true);
                }
            }
        }
        catch(Exception ex)
        {
            Response.Write("<script type='text/javascript'>alert('系统报错：" + ex.Message + "');window.close();</script>");
        }
    }
    /// <summary>
    /// 初始化打印页面
    /// </summary>
    /// <param name="printInfo">打印信息</param>
    /// <param name="isLastContainer">是否最后一个批次</param>
    /// <returns></returns>
    private string InitData(Dictionary<string, object> printInfo, bool isLastContainer)
    {
        var DP = ypBusiness.GetContainerPrintInfo(printInfo);
        isBank = Boolean.Parse(printInfo["IsBlank"].ToString());
        dtMain = DP.Tables["dtMain"];//批次主信息
        dtContainerStep = DP.Tables["dtContainerStep"];//批次工序列表
        dtSpecResource = DP.Tables["specResource"];//设备型号
        dtSpecCheckPoints = DP.Tables["dtCheckItemList"];//关键过程控制记录
        dtContainerAttributeDt = DP.Tables["containerAttributeDt"];//批次属性
        dtContainerSubContainer = DP.Tables["dtContainerSubContainer"];//子工序信息
        dtContainerStepAttributes = DP.Tables["dtContainerStepAttributes"];//批次工序属性信息 add zhunan 2022.1.19
        //dtContainerStepCheckNotes = DP.Tables["dtContainerStepCheckNotes"];//批次工序检验备注信息
        dtContainerSubInfo = DP.Tables["dtContainerSubInfo"];//批次的子工艺批次信息
        //关键过程序多人报工时，只在最后一行显示关键过程信息
        #region 同一工序多条报工记录处理
        //checkerNoEdit: 检验员没有录入过实测值
        if (dtSpecCheckPoints.Rows.Count > 0)
        {
            checkerNoEdit = dtSpecCheckPoints.Select("containerstepworkreportid IS NOT NULL").Length == 0 ? true : false;
        }

        dtContainerStep = common.MergeContainerStepWorkReport(dtContainerStep, checkerNoEdit);
        #endregion

        string strCurrHtml = string.Empty;
        strCurrHtml += BindHeader();//绑定第一个表头  
        strCurrHtml += BindContentTable();//绑定工序表格内容
        strCurrHtml = strCurrHtml.Replace("=TPages=", pages.ToString());//更新总页数
        if (pages % 2 != 0 && !isLastContainer) //如果页面为基数且不是最后一个批次
        {
            strCurrHtml += GetPaging() + GetPaging();
        }
        else
        {
            strCurrHtml += GetPaging();
        }
        return strCurrHtml;
    }
    /// <summary>
    /// 绑定表头
    /// </summary>
    /// <returns></returns>
    private string BindHeader()
    {
        DataRow drMain = dtMain.Rows[0];
        string strHeader = string.Empty;
        string originalstartdate = drMain["originalstartdate"].ToString();
        if (!string.IsNullOrWhiteSpace(originalstartdate))
        {
            originalstartdate = DateTime.Parse(originalstartdate).ToString("yyyy年MM月dd日");
        }
        strHeader += "<div class='specialTitle'>流水作业卡片</div>" + GetPageHead();
        strHeader += "<table class='specialHeader1'>";
        if (dtContainerSubContainer.Rows.Count > 0) //如果子工艺不为空，则绑定子工艺表头
        {
            rowHeight = 184;//重新计算起始内容高度（不包含建卡人员之后的行高）
            string process_No = drMain["Process_No"].ToString();//工艺规程编号
            if (process_No.Contains("CZ"))
            {
                process_No = process_No.Replace("CZ", "");
            }
            strHeader += string.Format("<tr><td>工艺规程号</td><td colspan='2'>{0}</td>", process_No);
            strHeader += string.Format("<td>表盘编号</td><td colspan='2'>{0}</td></tr>", drMain["YpContainerNo"].ToString());
            strHeader += "<tr><td style='width:170px;'>零件号</td><td style='width:175px;'>批次号</td><td>数量</td><td>报废数</td><td>废品顺序号</td><td>废品单号</td></tr>";
            foreach (DataRow item in dtContainerSubContainer.Rows)
            {
                if (rowHeight + 41 > totalHeight)//如果添加当前行高度后超过最大高度，则换页
                {
                    strHeader += "</table>";
                    strHeader = strHeader.Replace("specialHeader1", "specialHeaderPage");//替换样式，表格底部显示边框
                    if (pages == 1)
                    {
                        strHeader += GetBarCode(drMain["containerid"].ToString(), drMain["mfgordername"].ToString());//条形码
                    }
                    strHeader += GetPaging();
                    strHeader += GetPageHead();
                    rowHeight = 18;//页眉高度
                    strHeader += "<table class='specialHeader1'>";
                }
                strHeader += string.Format("<tr><td>{0}</td>", item["productname"].ToString());//零件号
                strHeader += string.Format("<td>{0}</td>", item["containername"].ToString());//批次号
                strHeader += string.Format("<td>{0}</td>", item["qty"].ToString());//数量
                strHeader += string.Format("<td>{0}</td>", "");//报废数
                strHeader += string.Format("<td>{0}</td>", "");//废品顺序号
                strHeader += string.Format("<td>{0}</td></tr>", "");//废品单号
                rowHeight += 41;
            }
            strHeader += "</table>";
            if (rowHeight + 31 > totalHeight)//再判断建卡人员那一行
            {
                if (pages == 1)
                {
                    strHeader += GetBarCode(drMain["containerid"].ToString(), drMain["mfgordername"].ToString());//条形码
                }
                strHeader += GetPaging();
                strHeader = strHeader.Replace("specialHeader1", "specialHeaderPage");//替换样式，表格底部显示边框
                strHeader += GetPageHead();
                rowHeight = 18;
            }
            strHeader += "<table class='specialHeader2'>";
            strHeader += string.Format("<tr><td>建卡人员</td><td style='width:150px'>{0}</td>", drMain["startemployeeName"].ToString());
            strHeader += string.Format(" <td>建卡日期</td><td style='width:150px'>{0}</td>", originalstartdate);
            strHeader += string.Format("<td>检验员</td><td style='width:150px'>{0}</td></tr></table>", drMain["techniqueFullname"].ToString());//检验员（取值审核员）
            rowHeight += 31;
            if (rowHeight + 93 > totalHeight)//再判断工序表头加一行的内容是否放得下一页
            {
                if (pages == 1)
                {
                    strHeader += GetBarCode(drMain["containerid"].ToString(), drMain["mfgordername"].ToString());//条形码
                }
                strHeader += GetPaging();
                strHeader = strHeader.Replace("specialHeader2", "specialHeaderPage");//替换样式，表格底部显示边框
                strHeader += GetPageHead();
                rowHeight = 18;
            }
            rowHeight += 62;
        }
        else
        {
            DataRow drAddr = dtContainerAttributeDt == null ? null : dtContainerAttributeDt.Select("userattributename='产地'").FirstOrDefault();//产地
            DataRow drTestBarNum = dtContainerAttributeDt == null ? null : dtContainerAttributeDt.Select("userattributename='试棒数'").FirstOrDefault();//试棒数
            DataRow drTestSliceNum = dtContainerAttributeDt == null ? null : dtContainerAttributeDt.Select("userattributename='试片数'").FirstOrDefault();//试片数
            strHeader += string.Format("<tr><td colspan='2'>工艺规程号</td><td colspan='2'>{0}</td></tr>", drMain["workflowname"].ToString());
            strHeader += string.Format("<tr><td style='width:175px;'>零件号</td><td style='width:175px;'>{0}</td>", drMain["productname"].ToString());
            strHeader += string.Format("<td style='width:175px;'>材料牌号</td><td>{0}</td></tr>", drMain["Materialtrademark"].ToString());
            strHeader += string.Format("<tr><td>器材编号</td><td>{0}</td>", "");
            strHeader += string.Format("<td>产地</td><td>{0}</td></tr>", drAddr == null ? "" : drAddr["attributevalue"].ToString());
            strHeader += string.Format("<tr><td>批次号</td><td>{0}</td>", drMain["YpContainerNo"].ToString());
            strHeader += string.Format("<td>零件数量<br />(不含试片、试棒)</td><td>{0}</td></tr>", drMain["qty"].ToString());
            strHeader += string.Format("<tr><td>试棒数</td><td>{0}</td>", drTestBarNum == null ? "" : drTestBarNum["attributevalue"].ToString());
            strHeader += string.Format("<td>试片数</td><td>{0}</td></tr></table>", drTestSliceNum == null ? "" : drTestSliceNum["attributevalue"].ToString());
            strHeader += "<table class='specialHeader2'>";
            strHeader += string.Format("<tr><td>建卡人员</td><td style='width:150px'>{0}</td>", drMain["startemployeeName"].ToString());
            strHeader += string.Format(" <td>建卡日期</td><td style='width:150px'>{0}</td>", originalstartdate);
            strHeader += string.Format("<td>检验员</td><td style='width:150px'>{0}</td></tr></table>", drMain["techniqueFullname"].ToString());//检验员（取值审核员）
        }
        return strHeader;
    }
    /// <summary>
    /// 绑定数据内容表格
    /// </summary>
    /// <returns></returns>
    private string BindContentTable()
    {
        DataRow drMain = dtMain.Rows[0];
        int containerStepCount = dtContainerStep.Rows.Count;//总的工序行数
        string strTable = string.Empty;
        //表头
        strTable += GetProcedureTableTitle();
        //填充数据
        for (int i = 0; i < containerStepCount; i++)
        {
            DataRow dr = dtContainerStep.Rows[i];
            var isPages = IsPageing(dr);
            if (isPages.Item1)//是否分页
            {
                strTable += isPages.Item2;//添加空白行
                strTable += "</table>";
                if (pages == 1)
                {
                    strTable += GetBarCode(drMain["containerid"].ToString(), drMain["mfgordername"].ToString());//条形码
                }
                strTable += GetPaging();
                strTable += GetPageHead();
                strTable += GetProcedureTableTitle();
            }
            if (dr["isSpotCheck"].ToString() == "1")//如果是关键工序
            {
                strTable += GetProcedureTableContent(dr);//获取工序
                strTable += "</table>";
                strTable += common.SetSpecKeyQualityControl(dr["specid"].ToString(), dr["reportid"].ToString(), checkerNoEdit, dtSpecCheckPoints, dtSpecResource, dr);//获取关键工序html代码
                //strTable += SetSpecKeyQualityControl(dr["specid"].ToString(), dr["reportid"].ToString(), checkerNoEdit);//获取关键工序html代码
                strTable += "<table class='specialTable2'>";
                //strTable += GetProcedureTableTitle(true);//获取隐藏的表头
            }
            else//不是关键工序，则插入工序即可
            {
                strTable += GetProcedureTableContent(dr);
                rowHeight += 31;
            }
        }
        strTable += GetBlankRow();
        strTable += "</table>";
        if (pages == 1)//结束时判断是不是处于第一页
        {
            strTable += GetBarCode(drMain["containerid"].ToString(), drMain["mfgordername"].ToString());//条形码
        }
        return strTable;
    }

    #region 工序扩展方法
    /// <summary>
    /// 获取空白行
    /// </summary>
    /// <returns></returns>
    private string GetBlankRow()
    {
        string strh = string.Empty;
        for (int h = rowHeight + 31; h < totalHeight; h += 31)
        {
            strh += "<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
        }
        return strh;
    }
    /// <summary>
    /// 是否需要分页
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    private Tuple<bool, string> IsPageing(DataRow dr)
    {
        string strBlank = string.Empty;
        if (rowHeight + 31 > totalHeight && dr["isSpotCheck"].ToString() != "1")//如果添加当前行高度后超过最大高度，则换页
        {
            rowHeight = 80;
            return new Tuple<bool, string>(true, strBlank);
        }
        else if (dr["isSpotCheck"].ToString() == "1")
        {
            int processCount, designCount;
            if (checkerNoEdit)
            {
                processCount = dtSpecCheckPoints.Select(String.Format("specid='{0}' and checktype = '3'", dr["specid"].ToString())).Length;
                designCount = dtSpecCheckPoints.Select(String.Format("specid='{0}' and checktype = '4'", dr["specid"].ToString())).Length;
            }
            else
            {
                processCount = dtSpecCheckPoints.Select(String.Format("specid='{0}' and checktype = '3' and containerstepworkreportid = '{1}'",
                    dr["specid"].ToString(), dr["reportid"].ToString())).Length;
                designCount = dtSpecCheckPoints.Select(String.Format("specid='{0}' and checktype = '4' and containerstepworkreportid = '{1}'",
                    dr["specid"].ToString(), dr["reportid"].ToString())).Length;
            }

            processCount = processCount == 0 ? 1 : processCount;
            designCount = designCount == 0 ? 1 : designCount;

            //212 = 工序行31px + 关键过程控制记录表头31px + 设备型号及编号90px + 设计参数首行30px + 过程参数首行30px
            if ((rowHeight + 212 + (30 * (processCount + designCount))) > totalHeight)
            {
                strBlank = GetBlankRow();
                rowHeight = 80 + 212 + (30 * (processCount + designCount));
                return new Tuple<bool, string>(true, strBlank);
            }
            rowHeight += 212 + (30 * (processCount + designCount));
        }
        return new Tuple<bool, string>(false, "");
    }
    /// <summary>
    /// 获取表头
    /// </summary>
    /// <returns></returns>
    private string GetProcedureTableTitle()
    {
        return @"<table class='specialTable'>
                      <tr><td rowspan='2'>工序号</td><td rowspan='2'>工序名称</td><td rowspan='2'>数量</td>
                      <td rowspan='2'>操作者</td><td rowspan='2'>日期</td><td colspan='4'>检验结果</td>
                      <td rowspan='2'>检验印</td><td rowspan='2'>备注</td></tr>
                      <tr><td>合格</td><td>报废</td><td>返修</td><td>超差</td></tr>";
    }
    /// <summary>
    /// 获取工序
    /// </summary>
    /// <param name="dr"></param>
    /// <param name="isSpan"></param>
    /// <returns></returns>
    private string GetProcedureTableContent(DataRow dr)
    {
        string containerId = dtMain.Rows[0]["containerId"].ToString();
        // 工序增加显示备注信息 add zhunan 2022.1.19
        string notes = "";
        if (dtContainerStepAttributes.Rows.Count > 0)
        {
            DataRow[] rows = dtContainerStepAttributes.Select(string.Format("workflowstepid='{0}'", dr["workflowstepid"].ToString()));
            foreach (DataRow item in rows)
            {
                notes += item["notes"].ToString() + ",";
            }
        }
        //工人备注
        notes += string.IsNullOrWhiteSpace(dr["worknote"].ToString()) ? "" : dr["worknote"].ToString() + ",";
        //检验备注
        notes += string.IsNullOrWhiteSpace(dr["checknote"].ToString()) ? "" : dr["checknote"].ToString() + ",";
        //追加子批次信息
        if (dtContainerSubInfo.Rows.Count > 0)
        {
            DataRow[] rows = dtContainerSubInfo.Select(string.Format("workflowstepid='{0}'", dr["workflowstepid"].ToString()));
            foreach (DataRow item in rows)
            {
                notes += item["rbtogetherflag"].ToString() + ",";
            }
        }
        ////备注追加工序检验备注信息 
        //if (dtContainerStepCheckNotes.Rows.Count > 0)
        //{
        //    DataRow[] rows = dtContainerStepCheckNotes.Select(string.Format("workflowstepid='{0}'", dr["workflowstepid"].ToString()));
        //    foreach (DataRow item in rows)
        //    {
        //        notes += item["checknote"].ToString() + ",";
        //    }
        //}
        if (dr["controlcode"].ToString() == "LY05" || dr["ISCOMMISSION"].ToString() == "1")//如果是外委
        {
            notes += "外委加工";
        }
        notes = notes.TrimEnd(',');
        string specno = dr["isSpotCheck"].ToString() == "1" ? "G" : "";//如果是关键工序，则在工序号前加G
        specno += dr["specno"].ToString();
        string reportEmployeeName = string.Empty;//操作者
        string checkemployeeName = string.Empty;//检验员
        string reportDate = string.Empty;//日期
        if (!isBank)
        {
            //如果是检验序或者是外委序，则显示横线，否则显示操作者
            reportEmployeeName = dr["lastcheck"].ToString() == "1" || dr["controlcode"].ToString() == "LY05" 
                ? "<div class='underLine' style='width: 30px;margin-left:10px'></div>" : dr["ReportEmployeeName"].ToString();
            //如果是外委序，则显示横线，否则显示检验员
            checkemployeeName = dr["controlcode"].ToString() == "LY05"
                ? "<div class='underLine' style='width: 80px;margin-left:10px'></div>" : dr["checkemployeename"].ToString();
            //日期不为空，则显示日期
            reportDate = !string.IsNullOrWhiteSpace(dr["reportdate"].ToString())
                ? DateTime.Parse(dr["reportdate"].ToString()).ToString("yyyy/MM/dd") : "";
        }
        return string.Format(@"<tr><td style='width:30px'>{0}</td>
                                    <td style='width:180px'>{1}</td>
                                    <td style='width:30px'>{2}</td>
                                    <td style='width:50px'>{3}</td>
                                    <td style='width:90px'>{4}</td>
                                    <td style='width:30px'>{5}</td>
                                    <td style='width:30px'>{6}</td>
                                    <td style='width:30px'>{7}</td>
                                    <td style='width:30px'>{8}</td>
                                    <td style='width:100px'>{9}</td>
                                    <td style='{10}'>{11}</td></tr>",
                                    specno, //工序号
                                    dr["opdesc"].ToString(), //工序名
                                    isBank ? "" : dr["ReportQty"].ToString(),//数量
                                    reportEmployeeName, //操作者
                                    reportDate,//日期
                                    isBank || dr["passqty"].ToString() == "0" ? "" : dr["passqty"].ToString(),//合格数
                                    isBank || dr["lossqty"].ToString() == "0" ? "" : dr["lossqty"].ToString(),//报废数
                                    isBank || dr["reworkqty"].ToString() == "0" ? "" : dr["reworkqty"].ToString(),//返修数
                                    isBank || dr["defectqty"].ToString() == "0" ? "" : dr["defectqty"].ToString(),//超差数
                                    checkemployeeName,//检验员
                                    (notes != "" && notes.Length > 11) ? "width:100px;text-align:left;font-size:10px;" : "width:100px;",
                                    isBank ? "" : notes);//备注
    }
    #endregion

    #region 通用方法
    /// <summary>
    /// 获取页眉
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    private string GetPageHead()
    {
        pages++;
        DataRow drMain = dtMain.Rows[0];
        string vision = "01";//版本
        if (!string.IsNullOrWhiteSpace(drMain["workflowrevision"].ToString()))//如果工艺版本不为空，则选择该版本
        {
            try
            {
                vision = int.Parse(drMain["workflowrevision"].ToString()) < 9 ? "0" + drMain["workflowrevision"].ToString() : drMain["workflowrevision"].ToString();
            }
            catch { }
        }
        else
        {
            if (!string.IsNullOrWhiteSpace(drMain["productrevision"].ToString()))//如果工艺版本为空，产品版本不为空，则选择该版本
            {
                try
                {
                    vision = int.Parse(drMain["productrevision"].ToString()) < 9 ? "0" + drMain["productrevision"].ToString() : drMain["productrevision"].ToString();
                }
                catch { }
            }
        }
        string strRight = string.Format(@"{0}-LK-{1}/=TPages=&V{2}", drMain["productname"].ToString(), pages, vision);
        return String.Format("<div class='rightHeadTip'>{0}</div>", strRight);
    }
    /// <summary>
    /// 获取分页
    /// </summary>
    /// <returns></returns>
    private string GetPaging()
    {
        return "<div class='paging'></div>";
    }
    /// <summary>
    /// 获取条形码
    /// </summary>
    /// <param name="containId">流水号</param>
    /// <param name="mfgordername">订单号</param>
    /// <returns></returns>
    private string GetBarCode(string containId, string mfgordername)
    {
        if (string.IsNullOrWhiteSpace(mfgordername))
        {
            return string.Format("<div style='height:70px;'><div class=barCode style='float:Right'>*{0}*</div> <div style='clear:both'></div></div>", containId);
        }
        return string.Format("<div style='height:70px;'><div class=barCode style='float:left'>*{0}*</div><div class=barCode style='float:Right'>*{1}*</div></div>", containId, mfgordername);
    }
    #endregion
}